package com.example.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/fota")
public class FOTAController {
	 private static final Logger logger = LoggerFactory.getLogger(FOTAController.class);
	/**
	 * 下载FOTA，文件存放默认路径jar包系统盘下fota文件夹
	 * @param request
	 * @param response
	 * @param fileName
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value="/get/{fileName}",method=RequestMethod.GET)
	public void getFOTA(HttpServletRequest request,HttpServletResponse response,@PathVariable String fileName)throws ServletException, IOException{
		fileName+=".bin";
		File file = new File(getPath(fileName));
		if(file.exists()){
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));  
	        InputStream in = null;  
	        OutputStream out = null;  
	        try {  
	            in = new FileInputStream(file);  
	            int len = 0;  
	             byte[] buffer = new byte[1024];  
	             out = response.getOutputStream();  
	            while((len = in.read(buffer)) > 0) {  
	                out.write(buffer,0,len);  
	            }  
	        }catch(Exception e) {  
	            throw e;  
	        }finally {  
	            if(in != null) {  
	                try {  
	                    in.close();  
	                }catch(Exception e) {  
	                    throw e;  
	                }  
	            }  
	        }  
		}
	}
	/**
	 * 获取文件路径
	 * @param fileName
	 * @return
	 */
	private String getPath(String fileName){
		/*String path = this.getClass().getResource("/").getPath();
		logger.debug(path);
		if(path!=null&&path.length()>2)*/
			String	path = "c:\\fota\\"+fileName;
		return path;
	}
}
